import React, { useCallback, useMemo } from 'react';
import { connect, ConnectedProps } from 'react-redux';
import { Input, Dropdown, Menu, Timeline } from 'antd';
import { Link } from 'react-router-dom';

import { SOURCE } from 'utils/constant';
import Logo from 'src/favicon.svg';
import { historySvg, favoriteSvg } from 'assets/svg';
import { usrPng } from 'assets/png';
import { formateTimeline } from 'utils/timelineFormate';
import { RootState } from 'src/app/rootReducer';
import { usrInfoSelector, usrSourceSelector, epicActions as usrEpics } from 'src/redux/usr';
import { epicActions as searchEpics, searchKeySelector, actions as searchActions } from 'src/redux/search';
import { actions as otherActions } from 'src/redux/other';
import { watchHistorySelector } from 'src/redux/watch';

import './index.css';

const { Search } = Input;

type NavbarType = ReduxProps & {
  needSource?: boolean;
};

export const Web: React.FC<NavbarType> = ({
  router,
  searchKey,
  watchHistory,
  usrSource,
  setCurrentSource,
  loadAllSearchSource,
  gotSearch,
  setSearchKey,
  clearSearchDetails,
  setCancelAction,
  needSource = true,
}) => {
  const searchHandle = useCallback(
    (search: string) => {
      if (!search) return;

      setCancelAction('navbarCancel');
      if (!router.location.pathname.includes('/search')) {
        gotSearch();
      }
      clearSearchDetails();
      setSearchKey(search);
      loadAllSearchSource('&wd=' + search);
    },
    [clearSearchDetails, gotSearch, loadAllSearchSource, router.location.pathname, setCancelAction, setSearchKey],
  );

  const menu = useMemo(() => {
    const onClick = ({ key }: { key: string }) => {
      setCancelAction('cancel');
      const select = SOURCE.get(key);
      setCurrentSource({ label: key, address: select! });
    };

    return (
      <Menu onClick={onClick}>
        {Array.from(SOURCE.keys()).map((key: string) => {
          return (
            <Menu.Item key={key}>
              <span>{key}</span>
            </Menu.Item>
          );
        })}
        {/* <Menu.Divider />
        <Menu.Item key="create">添加新视频源+</Menu.Item> */}
      </Menu>
    );
  }, [setCancelAction, setCurrentSource]);

  const timeline = useMemo(() => {
    const formatTimeline = formateTimeline(watchHistory);

    return (
      <div className="timeline-container">
        <div className="timeline-header">历史记录</div>
        <div className="timeline-body">
          <Timeline pending={false}>
            {formatTimeline.map((tl) => (
              <Timeline.Item color="gray" key={tl.time}>
                <div>{tl.time}</div>
                {tl.historys.map((history) => (
                  <div key={history.movieName + history.watchDate}>{history.movieName}</div>
                ))}
              </Timeline.Item>
            ))}
          </Timeline>
        </div>
        <div className="timeline-footer">查看全部记录</div>
      </div>
    );
  }, [watchHistory]);

  return (
    <div className="navbar-web-contaier">
      <span className="navbar-web-contaier-item">
        <Link to="/home">
          <span className="navbar-web-logo">
            <img src={Logo} alt="logo" />
          </span>
          <span className="navbar-web-logo-name">
            <span>下饭视频</span>
            <span>美好恰饭时光 </span>
          </span>
        </Link>

        {needSource ? (
          <span className="navbar-web-source-name">
            <span>
              当前视频源：
              <Dropdown overlay={menu} placement="bottomCenter">
                <p className="ant-dropdown-link">{usrSource.currentSource.label}</p>
              </Dropdown>
            </span>
          </span>
        ) : null}
      </span>

      <span className="navbar-web-contaier-item">
        <Search
          defaultValue={searchKey}
          className="navbar-web-search"
          placeholder="搜电影、电视剧"
          allowClear
          enterButton
          size="large"
          onSearch={searchHandle}
        />
      </span>

      <span className="navbar-web-contaier-item self-info">
        <span className="history-img">
          <Dropdown overlay={timeline} placement="bottomCenter">
            <img src={historySvg} alt="history" />
          </Dropdown>
        </span>
        <span className="favourite-img">
          <img src={favoriteSvg} alt="favourite" />
        </span>
        <span className="usr-img">
          <img src={usrPng} alt="usr" />
        </span>
      </span>
    </div>
  );
};

const connector = connect(
  (state: RootState) => ({
    usrInfo: usrInfoSelector(state),
    watchHistory: watchHistorySelector(state),
    usrSource: usrSourceSelector(state),
    searchKey: searchKeySelector(state),
    router: state.router,
  }),
  {
    setCurrentSource: usrEpics.setCurrentSource,
    loadAllSearchSource: searchEpics.loadAllSearchSource,
    clearSearchDetails: searchEpics.clearSearchDetails,
    setSearchKey: searchActions.setSearchKey,
    gotSearch: searchEpics.gotoSearch,
    setCancelAction: otherActions.setCancelAction,
  },
);
type ReduxProps = ConnectedProps<typeof connector>;
export const NavbarWeb = connector(Web);

export const NavbarMobile = () => {
  return <span className="navbar-web-logo">{<img src={Logo} />}</span>;
};
